import axios from 'axios';
axios.defaults.baseURL = 'http://127.0.0.1:3000';

if (!localStorage.getItem('refreshToken')) {
  console.log('没有refreshToken');
  if (localStorage.getItem('accessToken')) {
    // localStorage.removeItem('accessToken');
    localStorage.clear();
  }
} else {
  console.log('有refreshToken');
  if (!localStorage.getItem('accessToken')) {
    console.log('没有accessToken');
    axios.post('/refresh', { refreshToken: localStorage.getItem('refreshToken') }).then(i => {
      localStorage.setItem('accessToken', i.data.accessToken);
      // window.history.go(window.location.pathname);
      // console.log(window.location.pathname, 'location.pathname')
    });
  }
}

// 添加请求拦截器
axios.interceptors.request.use((config) => {
  // 在发送请求之前做些什么
  // console.log(config.method, config.url);
  // 携带token
  const token = localStorage.getItem('accessToken');
  console.log(token, "token");
  if (token) {
    config.headers.Authorization = 'Bearer ' + token;
  }
  console.log(config, 'config')
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use((response) => {
  console.log(response.data, 'response.data');
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  if (response.data.code === 401) {
    //token失败
    // localStorage.removeItem('accessToken');
    localStorage.clear();
    window.location.href = '/login';
    // return
  }
  return response;
}, 
(error) => {
  console.log(error.request, 'error.request');
  console.log(error.response, 'error.response');
  // 超出 2xx 范围的状态码都会触发该函数。
  console.log(error, 'error')
  // 对响应错误做点什
  if (error.response?.status === 401) {
    axios.post('/refresh', { refreshToken: localStorage.getItem('refreshToken') }).then(i => {
      localStorage.setItem('accessToken', i.data.accessToken);
      // window.history.go(-1)
    });
  }
  if (error.status === 403) {
    window.location.href = '/login';
    localStorage.clear();
  }
  return Promise.reject(error);
});

// axios.interceptors.response.use(
//   (response) => response,
//   (error) => {
//     // 处理非 2xx 状态码
//     if (error.response) {
//       console.log('错误状态码:', error.response.status);
//     } else {
//       console.log('请求未完成:', error.message);
//     }
//     return Promise.reject(error);
//   }
// );

export default axios;